﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Configuration;
using System.Data;

namespace DBAccess
{
    /// <summary>
    /// 
    /// </summary>
    public class DAL
    {
        private static DAL instance;

        private DataSources dataSource = DataSources.Nothing;
        private string connectionString;

        DbProviderFactory provider;
        DbConnection connection;
        DbCommand command;
        DataSet dataSet;

        #region Get instance
        /// <summary>
        /// Returns instance setup to connect to MSSQL server
        /// </summary>
        /// <returns></returns>
        public static DAL GetMSSQLInstance()
        {
            if (instance == null)
            {
                instance = new DAL();
                instance.dataSource = DataSources.MSSQL;

            }
            return instance;
        }
        /// <summary>
        /// Returns instance setup to connect to MSSQL server
        /// </summary>
        /// <returns></returns>
        public static DAL GetMySQLInstance()
        {
            if (instance == null)
            {
                instance = new DAL();
                instance.dataSource = DataSources.MySQL;

            }
            return instance;
        }
        /// <summary>
        /// Returns instance of DAL. If instance isn't created yet creates new one and tries
        /// to read the datasource/provider name and connection string from app.config file.
        /// </summary>
        /// <returns></returns>
        public static DAL GetInstance()
        {
            if (instance == null)
                instance = new DAL();
            if (instance.dataSource == DataSources.Nothing)
            {
                //try to setup provider name
                instance.GetDataSourceFromConfiguration();
            }
            if (instance.ConnectionString == null || instance.ConnectionString == string.Empty)
            {
                instance.GetConnectionStringFromConfiguration("DALConnectionString");
            }
            return instance;
        }
        #endregion

        #region Properties
        public string Query { get; set; }

        public string ConnectionString
        {
            get { return connectionString; }
            set
            {
                connectionString = value;
                if (connection != null)
                    connection.ConnectionString = ConnectionString;
            }
        }

        public DataSources DataSource
        {
            get { return dataSource; }
            set
            {
                dataSource = value;
                ChangeDataSource();
            }
        }
        /// <summary>
        /// Get result of last query.
        /// </summary>
        public DataSet Data
        {
            get { return dataSet; }
        }
        #endregion

        #region Data access function
        /// <summary>
        /// Execute SelectQuery and return dataset filled with data returned from the database
        /// </summary>
        /// <returns></returns>
        public DataSet GetData()
        {
            return GetData(Query);
        }
        /// <summary>
        /// Execute SelectQuery and return dataset filled with data returned from the database
        /// </summary>
        /// <returns></returns>
        public DataSet GetData(List<object> parameters)
        {
            return GetData(Query, parameters);
        }
        /// <summary>
        /// Execute query and return dataset filled with data returned from the database
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataSet GetData(string query)
        {
            if (query == null || query == string.Empty)
                throw new ArgumentException("Query cannot be null.");
            if (provider == null)
                ConfigureInstance();
            command = provider.CreateCommand();
            command.Connection = connection;
            command.CommandText = query;
            command.CommandType = CommandType.Text;

            dataSet = new DataSet();
            DbDataAdapter ad = provider.CreateDataAdapter();
            ad.SelectCommand = command;

            connection.Open();
            ad.Fill(dataSet);
            connection.Close();

            return dataSet;
        }

        /// <summary>
        /// Execute query and return dataset filled with data returned from the database
        /// </summary>
        /// <param name="query"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public DataSet GetData(string query, List<object> parameters)
        {
            if (query == null || query == string.Empty)
                throw new ArgumentException("Query cannot be null.");

            command = provider.CreateCommand();
            command.Connection = connection;
            command.CommandText = query;
            command.CommandType = CommandType.Text;
            for (int i = 0; i < parameters.Count; i++)
            {
                DbParameter p = provider.CreateParameter();
                p.ParameterName = "@param" + i.ToString();
                p.Value = parameters[i];
                command.Parameters.Add(p);
            }

            dataSet = new DataSet();
            DbDataAdapter ad = provider.CreateDataAdapter();
            ad.SelectCommand = command;

            connection.Open();
            ad.Fill(dataSet);
            connection.Close();

            return dataSet;
        }

        /// <summary>
        /// Execute query and return first column of first row as string.
        /// If nothing is returned from db returns empty string.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public string GetScalar(string query)
        {
            GetData(query);
            if (dataSet != null && dataSet.Tables.Count > 0)
            {
                if (dataSet.Tables[0].Rows.Count > 0)
                    if (dataSet.Tables[0].Rows[0][0] != null)
                        return dataSet.Tables[0].Rows[0][0].ToString();
            }
            return string.Empty;
        }
        /// <summary>
        /// Execute query and return first column of first row as string.
        /// If nothing is returned from db returns empty string.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public string GetScalar(string query, List<object> parameters)
        {
            GetData(query, parameters);
            if (dataSet != null && dataSet.Tables.Count > 0)
            {
                if (dataSet.Tables[0].Rows.Count > 0)
                    if (dataSet.Tables[0].Rows[0][0] != null)
                        return dataSet.Tables[0].Rows[0][0].ToString();
            }
            return string.Empty;
        }
        /// <summary>
        /// Execute query and return given column of first row as string.
        /// If nothing is returned it throws ArgumentException
        /// </summary>
        /// <exception cref="">Throws argumentException if column index is wrong</exception>
        /// <param name="querym"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        public string GetScalar(string query, int column)
        {
            GetData(query);
            if (dataSet != null && dataSet.Tables.Count > 0)
            {
                if (dataSet.Tables[0].Rows.Count > 0)
                {
                    if (column < 0 || column >= dataSet.Tables[0].Columns.Count)
                        throw new ArgumentException("Wrong column number");
                    if (dataSet.Tables[0].Rows[0][column] != null)
                        return dataSet.Tables[0].Rows[0][column].ToString();
                }
            }
            return string.Empty;
        }
        /// <summary>
        /// Execute query(set in DAL.SelectQuery) and return first column of first row as string.
        /// If nothing is returned from db returns empty string.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public string GetScalar()
        {
            GetData();
            if (dataSet != null && dataSet.Tables.Count > 0)
            {
                if (dataSet.Tables[0].Rows.Count > 0)
                    if (dataSet.Tables[0].Rows[0][0] != null)
                        return dataSet.Tables[0].Rows[0][0].ToString();
            }
            return string.Empty;
        }
        /// <summary>
        /// Execute query(set in DAL.SelectQuery) and return first column of first row as string.
        /// If nothing is returned from db returns empty string.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public string GetScalar(List<object> parameters)
        {
            GetData(parameters);
            if (dataSet != null && dataSet.Tables.Count > 0)
            {
                if (dataSet.Tables[0].Rows.Count > 0)
                    if (dataSet.Tables[0].Rows[0][0] != null)
                        return dataSet.Tables[0].Rows[0][0].ToString();
            }
            return string.Empty;
        }
        /// <summary>
        /// Execute query(set in DAL.SelectQuery) and return given column of first row as string.
        /// If nothing is returned it throws ArgumentException
        /// </summary>
        /// <exception cref="">Throws argumentException if column index is wrong</exception>
        /// <param name="querym"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        public string GetScalar(int column)
        {
            GetData();
            if (dataSet != null && dataSet.Tables.Count > 0)
            {
                if (dataSet.Tables[0].Rows.Count > 0)
                {
                    if (column < 0 || column >= dataSet.Tables[0].Columns.Count)
                        throw new ArgumentException("Wrong column number");
                    if (dataSet.Tables[0].Rows[0][column] != null)
                        return dataSet.Tables[0].Rows[0][column].ToString();
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// Execute query(set in DAL.SelectQuery) and return first column of first row as int.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public int GetInt(string query)
        {
            int tmp;
            if (int.TryParse(GetScalar(query), out tmp) == true)
                return tmp;
            else
                throw new ArithmeticException("Cannot convert results of query: " + query + " to integer.\n\r Results: " + GetScalar(query));
        }
        /// <summary>
        /// Execute query(set in DAL.SelectQuery) and return first column of first row as int.
        /// </summary>
        /// <returns></returns>
        public int GetInt()
        {
            int tmp;
            if (int.TryParse(GetScalar(), out tmp) == true)
                return tmp;
            else
                throw new ArithmeticException("Cannot convert results of query: " + Query + " to integer.\n\r Results: " + GetScalar());
        }
        /// <summary>
        /// Execute query(set in DAL.SelectQuery) and return first column of first row as int.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public int GetInt(string query, List<object> parameters)
        {
            int tmp;
            if (int.TryParse(GetScalar(query, parameters), out tmp) == true)
                return tmp;
            else
                return -1;
                //throw new ArithmeticException("Cannot convert results of query: " + query + " to integer.\n\r Results: " + GetScalar(query));
        }
        /// <summary>
        /// Execute query(set in DAL.SelectQuery) and return first column of first row as int.
        /// </summary>
        /// <returns></returns>
        public int GetInt(List<object> parameters)
        {
            int tmp;
            if (int.TryParse(GetScalar(parameters), out tmp) == true)
                return tmp;
            else
                throw new ArithmeticException("Cannot convert results of query: " + Query + " to integer.\n\r Results: " + GetScalar());
        }

        /// <summary>
        /// Execute query(set in DAL.SelectQuery) and return first column of first row as int.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public double GetDouble(string query)
        {
            double tmp;
            if (double.TryParse(GetScalar(query), out tmp) == true)
                return tmp;
            else
                throw new ArithmeticException("Cannot convert results of query: " + query + " to double.\n\r Results: " + GetScalar(query));
        }
        /// <summary>
        /// Execute query(set in DAL.SelectQuery) and return first column of first row as int.
        /// </summary>
        /// <returns></returns>
        public double GetDouble()
        {
            double tmp;
            if (double.TryParse(GetScalar(), out tmp) == true)
                return tmp;
            else
                throw new ArithmeticException("Cannot convert results of query: " + Query + " to double.\n\r Results: " + GetScalar());
        }
        /// <summary>
        /// Execute query(set in DAL.SelectQuery) and return first column of first row as int.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public double GetDouble(string query, List<object> parameters)
        {
            double tmp;
            if (double.TryParse(GetScalar(query, parameters), out tmp) == true)
                return tmp;
            else
                throw new ArithmeticException("Cannot convert results of query: " + query + " to double.\n\r Results: " + GetScalar(query));
        }
        /// <summary>
        /// Execute query(set in DAL.SelectQuery) and return first column of first row as int.
        /// </summary>
        /// <returns></returns>
        public double GetDouble(List<object> parameters)
        {
            double tmp;
            if (double.TryParse(GetScalar(parameters), out tmp) == true)
                return tmp;
            else
                throw new ArithmeticException("Cannot convert results of query: " + Query + " to double.\n\r Results: " + GetScalar());
        }

        public int NumberOfRows()
        {
            return NumberOfRows(Query);
        }
        public int NumberOfRows(string query)
        {
            GetData();
            if (dataSet.Tables.Count > 0)
                return dataSet.Tables[0].Rows.Count;
            return 0;
        }
        public int NumberOfRows(List<object> parameters)
        {
            return NumberOfRows(Query);
        }
        public int NumberOfRows(string query, List<object> parameters)
        {
            GetData(query, parameters);
            if (dataSet.Tables.Count > 0)
                return dataSet.Tables[0].Rows.Count;
            return 0;
        }
        #endregion

        #region Insert data functions
        public void InsertData(List<object> parameters)
        {
            InsertData(Query, parameters);
        }
        public void InsertData(string query, List<object> parameters)
        {
            if (query == null || query == string.Empty)
                throw new ArgumentException("Query cannot be null.");

            command = provider.CreateCommand();
            command.Connection = connection;
            command.CommandText = query;
            command.CommandType = CommandType.Text;
            for (int i = 0; i < parameters.Count; i++)
            {
                DbParameter p = provider.CreateParameter();
                p.ParameterName = "@param" + i.ToString();
                p.Value = parameters[i];
                command.Parameters.Add(p);
            }
            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }
        #endregion

        #region Update data functions
        public int UpdateData(List<object> parameters)
        {
            return UpdateData(Query, parameters);
        }
        public int UpdateData(string query)
        {
            if (query == null || query == string.Empty)
                throw new ArgumentException("Query cannot be null.");

            command = provider.CreateCommand();
            command.Connection = connection;
            command.CommandText = query;
            command.CommandType = CommandType.Text;

            connection.Open();
            int c = command.ExecuteNonQuery();
            connection.Close();
            return c;
        }
        public int UpdateData(string query, List<object> parameters)
        {
            if (query == null || query == string.Empty)
                throw new ArgumentException("Query cannot be null.");

            command = provider.CreateCommand();
            command.Connection = connection;
            command.CommandText = query;
            command.CommandType = CommandType.Text;
            for (int i = 0; i < parameters.Count; i++)
            {
                DbParameter p = provider.CreateParameter();
                p.ParameterName = "@param" + i.ToString();
                p.Value = parameters[i];
                command.Parameters.Add(p);
            }
            connection.Open();
            int c = command.ExecuteNonQuery();
            connection.Close();
            return c;
        }
        #endregion

        #region Delete data functions
        public void DeleteData(List<object> parameters)
        {
            DeleteData(Query, parameters);
        }
        public void DeleteData(string query)
        {
            if (query == null || query == string.Empty)
                throw new ArgumentException("Query cannot be null.");

            command = provider.CreateCommand();
            command.Connection = connection;
            command.CommandText = query;
            command.CommandType = CommandType.Text;

            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }

        public void DeleteData(string query, List<object> parameters)
        {
            if (query == null || query == string.Empty)
                throw new ArgumentException("Query cannot be null.");

            command = provider.CreateCommand();
            command.Connection = connection;
            command.CommandText = query;
            command.CommandType = CommandType.Text;
            for (int i = 0; i < parameters.Count; i++)
            {
                DbParameter p = provider.CreateParameter();
                p.ParameterName = "@param" + i.ToString();
                p.Value = parameters[i];
                command.Parameters.Add(p);
            }
            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }
        #endregion

        #region Configuration functions
        /// <summary>
        /// Search for key data source in default configuration file.
        /// </summary>
        protected void GetDataSourceFromConfiguration()
        {
            if (ConfigurationManager.AppSettings != null)
                if (ConfigurationManager.AppSettings["Provider"] != null)
                {
                    switch (ConfigurationManager.AppSettings["Provider"].ToLower())
                    {
                        case "mssql": dataSource = DataSources.MSSQL; break;
                        case "mysql": dataSource = DataSources.MySQL; break;
                        case "filecsv": dataSource = DataSources.FileCSV; break;
                        default:
                            dataSource = DataSources.Nothing; break;
                    }
                    ChangeDataSource();
                    return;
                }
            throw new ArgumentException("There is no provider key in appSetting in default app.config");
        }
        protected void GetConnectionStringFromConfiguration(string name)
        {
            if (ConfigurationManager.ConnectionStrings != null)
            {
                if (ConfigurationManager.ConnectionStrings[name] != null)
                {
                    ConnectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
                }
            }
        }

        #endregion

        private void ChangeDataSource()
        {
            switch (dataSource)
            {
                case DataSources.MSSQL:
                    provider = DbProviderFactories.GetFactory("System.Data.SqlClient");
                    break;
                case DataSources.MySQL:
                    provider = DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
                    break;
                case DataSources.FileCSV:
                    throw new NotImplementedException();
                default:
                    throw new ArgumentException("DataSource cannot be set to Nothing");
            }
            connection = provider.CreateConnection();
            if (ConnectionString != null)
                connection.ConnectionString = ConnectionString;
            else
                connection.ConnectionString = string.Empty;
        }
        private void ConfigureInstance()
        {
            if (dataSource == DataSources.Nothing)
            {
                //try to setup provider name
                GetDataSourceFromConfiguration();
            }
            if (ConnectionString == null || ConnectionString == string.Empty)
            {
                GetConnectionStringFromConfiguration("DALConnectionString");
            }
        }
    }
}